/* AddressBar.java
 * Author: liuex
 * 2007-12-22 ����02:33:04
 *
 * Note: 
 */
package org.lex.explorer.address;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JTextField;

import org.lex.explorer.AbstractExplorer;
import org.lex.io.IO;
import org.lex.swing.SelectAllWhenGainFocus;
import org.lex.utils.SystemProperties;


public class AddressBar extends AbstractExplorer {
	private File directory = null;
	private JTextField addressTextField;

	public AddressBar() {
		this(new File(SystemProperties.userHome()));
	}

	public AddressBar(File directory) {
		super();
		this.directory = directory;
		this.initialize();
	}

	@Override
	public File getDirectory() {
		return this.directory;
	}

	@Override
	public void setDirectory(File directory, boolean fireEvent) {
		log.trace("change to directory: " + directory.toString());
		File old = this.directory;
		this.directory = directory;
		this.addressTextField.setText(this.directory.getPath());
		if (true == fireEvent)
			this.fireDirectoryChange(old, directory);
	}

	private void initialize() {
		this.setLayout(new BorderLayout());
		this.add(getAddressTextField(), BorderLayout.CENTER);
	}

	private JTextField getAddressTextField() {
		if (addressTextField == null) {
			addressTextField = new JTextField();
			addressTextField.setText(IO.getCanonicalPath(this.directory));
			addressTextField.addFocusListener(SelectAllWhenGainFocus.getInstance());
			addressTextField.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					String text = addressTextField.getText().trim();
					File file = new File(text);
					if (file.exists() && file.isDirectory()) {
						File old = directory;
						directory = file;
						addressTextField.setText(IO.getCanonicalPath(directory));
						fireDirectoryChange(old, file);
					}
				}
			});
		}
		return addressTextField;
	}
}
